<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="95px">
      <el-form-item label="日期" prop="title">
        <el-date-picker v-model="timeRanges" type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" style="width: 340px;" @keyup.enter.native="handleQuery"></el-date-picker>
      </el-form-item>
      <el-form-item label="产品编码" prop="productCode">
        <el-input v-model="queryParams.productCode" @keyup.enter.native="handleQuery" placeholder="请输入产品编码" style="width: 100%"></el-input>
      </el-form-item>
      <el-form-item label="店铺" prop="shop">
        <el-select v-model="queryParams.shop" @keyup.enter.native="handleQuery" filterable placeholder="请选择店铺" clearable style="width: 100%;">
          <el-option v-for="(item, index) in ['乐艺贴饰', '始发旗舰店', '济南中呈商贸有限公司', '九变定制旗舰店', '九变定制文具', '搜途办公专营店', '哲众旗舰店', 'jnjb2008', '派依倍旗舰店', '智詹官方旗舰店', '锦玉轩家纺家具官方旗舰店', '中奥数码电器', '迪士普数码电器官方旗舰店', '素锦留旗舰店', '起辰', '星耀创意贴饰', '翔启扬旗舰店', '丝乐爽旗舰店', '雨恋冰纯旗舰店', '铎金办公专营店', '智呈旗舰店', '世格创意贴饰', '呈讯旗舰店', '华鲁搜途旗舰店', '智宏汇旗舰店', '展迪优文具馆', '中艺创意家居', '董东东2013', '广格宏家纺家具官方旗舰店', '美格鸿旗舰店', '格莱美海报工厂', '九鼎铎金官方旗舰店', '知迅唐办公用品旗舰店', '中展航标识', '中弘图韵官方旗舰店', '宝菁旗舰店', '中奥晋呈旗舰店', '中弘海报2', '屹呈旗舰店', '九鼎铎金旗舰店', '益讯旗舰店', '中慧达旗舰店', '中利呈旗舰店', '画萌文教用具旗舰店']"
                     :key="index" :label="item" :value="item"/>
        </el-select>
      </el-form-item>
      <el-form-item label="是否加急" prop="emergency">
        <el-select v-model="queryParams.emergency" placeholder="请选择是否加急" filterable clearable style="width: 100%;">
          <el-option v-for="dict in dict.type.emergency" :key="dict.value" :label="dict.label" :value="dict.value"/>
        </el-select>
      </el-form-item>
      <el-form-item label="发布人" prop="userId">
        <el-select v-model="queryParams.userId" placeholder="请选择发布人" filterable clearable @keyup.enter.native="handleQuery" style="width: 100%;">
          <el-option v-for="dict in userIdList" :key="dict.user_id" :label="dict.nickName" :value="dict.user_id"/>
        </el-select>
      </el-form-item>
      <el-form-item label="模版接取人员" label-width="100px" prop="receiveTasksPerson">
        <el-select v-model="queryParams.receiveTasksPerson" placeholder="请选择模版接取人员" filterable clearable @keyup.enter.native="handleQuery" style="width: 100%;">
          <el-option v-for="dict in receiveTasksPersonList" :key="dict.receive_tasks_person" :label="dict.nickName" :value="dict.receive_tasks_person"/>
        </el-select>
      </el-form-item>
      <el-form-item label="美工和SKU接取人员" label-width="100px" prop="artistAllocation">
        <el-select v-model="queryParams.artistAllocation" placeholder="请选择美工和SKU接取人员" filterable clearable @keyup.enter.native="handleQuery" style="width: 100%;">
          <el-option v-for="dict in artistAllocationList" :key="dict.artist_allocation" :label="dict.nickName" :value="dict.artist_allocation"/>
        </el-select>
      </el-form-item>
      <el-form-item label="模版拼版接取人员" label-width="100px" prop="make">
        <el-select v-model="queryParams.make" placeholder="请选择模版拼版接取人员" filterable clearable @keyup.enter.native="handleQuery" style="width: 100%;">
          <el-option v-for="dict in makeUpList" :key="dict.make" :label="dict.nickName" :value="dict.make"/>
        </el-select>
      </el-form-item>
      <el-form-item label="状态" label-width="100px" prop="make">
        <el-select v-model="queryParams.statusMap" placeholder="请选择状态" filterable clearable @keyup.enter.native="handleQuery" style="width: 100%;">
          <el-option v-for="(item, index) in ['模版未接取', '模版已接取未完成', '模版待签字', '美工未接取', '美工已接取未完成', '美工待签字', '拼版未接取', '拼版已接取未完成', 'SKU未接取', 'SKU已接取未完成', 'SKU待签字']" :key="index" :label="item" :value="index"/>
        </el-select>
      </el-form-item>
      <el-form-item label="是否上架" label-width="100px" prop="make">
        <el-select v-model="queryParams.staff" placeholder="请选择状态" filterable clearable @keyup.enter.native="handleQuery" style="width: 100%;">
          <el-option v-for="dict in [{label: '是', value: 0}, {label: '否', value: 1}]" :key="dict.value" :label="dict.label" :value="dict.value"/>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8" ref="toolbar">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          @click="handleAdd"
          v-hasPermi="['business:taskerp:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['business:taskerp:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['business:taskerp:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" @click="transferTask()" v-hasPermi="['business:taskerp:transfer']">转交任务</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" @click="assignTasks()" v-hasPermi="['business:taskerp:transfer']">批量分配任务</el-button>
      </el-col>
      <!--      <el-col :span="1.5">-->
      <!--        <el-button-->
      <!--          type="warning"-->
      <!--          plain-->
      <!--          icon="el-icon-download"-->
      <!--          @click="handleExport"-->
      <!--          v-hasPermi="['business:taskerp:export']"-->
      <!--        >导出</el-button>-->
      <!--      </el-col>-->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="taskerpList" :height = "tableHeight" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="产品编码" fixed align="center" prop="productCode" />
      <el-table-column label="发布人员" align="center" prop="remark" />
      <el-table-column label="日期" align="center" prop="title" />
      <el-table-column label="类别" align="center" prop="type">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.taskerp_type" :value="scope.row.type"/>
        </template>
      </el-table-column>
      <el-table-column label="店铺" align="center" prop="shop" />
      <el-table-column label="是否加急" align="center" prop="emergency">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.emergency" :value="scope.row.emergency"/>
        </template>
      </el-table-column>
      <el-table-column label="参考链接1" align="center" prop="referenceLink">
        <template slot-scope="scope">
          <el-button type="text" v-if="scope.row.referenceLink" @click="copyUrl(scope.row.referenceLink)">复制链接</el-button>
          <el-button type="text" v-if="scope.row.referenceLink" @click="toUrl(scope.row.referenceLink)" style="margin: 0;">链接跳转</el-button>
        </template>
      </el-table-column>
      <el-table-column label="参考链接2" align="center" prop="referenceLinkOne">
        <template slot-scope="scope">
          <el-button type="text" v-if="scope.row.referenceLinkOne" @click="copyUrl(scope.row.referenceLinkOne)">复制链接</el-button>
          <el-button type="text" v-if="scope.row.referenceLinkOne" @click="toUrl(scope.row.referenceLinkOne)" style="margin: 0;">链接跳转</el-button>
        </template>
      </el-table-column>
      <el-table-column label="参考链接3" align="center" prop="referenceLinkTwo">
        <template slot-scope="scope">
          <el-button type="text" v-if="scope.row.referenceLinkTwo" @click="copyUrl(scope.row.referenceLinkTwo)">复制链接</el-button>
          <el-button type="text" v-if="scope.row.referenceLinkTwo" @click="toUrl(scope.row.referenceLinkTwo)" style="margin: 0;">链接跳转</el-button>
        </template>
      </el-table-column>
      <el-table-column label="参考图" align="center" prop="referenceImage">
        <template slot-scope="scope">
          <image-preview :src="scope.row.referenceImage" style="width: 50%;height: 50%;"/>
        </template>
      </el-table-column>
      <el-table-column label="模版数量" align="center" prop="templatesNum" />
      <el-table-column label="模版要求" align="center" width="120px" prop="templateReq" />
      <el-table-column label="尺寸要求" align="center" width="120px" prop="sizeReq" />
      <el-table-column label="主图详情要求" align="center" width="120px" prop="mainImgReq" />
      <el-table-column label="是否需要主图" align="center" width="120px">
        <template slot-scope="scope">
          <span v-if="scope.row.type == 0" v-for="(item, index) in ['是', '否'][scope.row.mainImages]" :key="index">{{ item }}</span>
        </template>
      </el-table-column>
      <el-table-column label="类目要求" align="center" width="120px" prop="categoryReq" />
      <!--      <el-table-column label="附件" align="center" prop="attachment">-->
      <!--        <template slot-scope="scope">-->
      <!--          <image-preview :src="scope.row.attachment" style="width: 50%;height: 50%;"/>-->
      <!--        </template>-->
      <!--      </el-table-column>-->
      <el-table-column label="类型" align="center" prop="complexity">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.complexity" :value="scope.row.complexity"/>
        </template>
      </el-table-column>
      <!--      <el-table-column label="是否通过" align="center" prop="didItPass">-->
      <!--        <template slot-scope="scope">-->
      <!--          <span v-for="item in [{ value: '0', label: '驳回'}, { value: '1', label: '通过'}]" :key="item.value" v-if="scope.row.examineAttachment == item.value">{{ item.label }}</span>-->
      <!--        </template>-->
      <!--      </el-table-column>-->
      <el-table-column label="审核附件" align="center" prop="examineAttachment">
        <template slot-scope="scope">
          <image-preview v-if="scope.row.examineAttachment" :src="scope.row.examineAttachment" style="width: 50%;height: 50%;"/>
        </template>
      </el-table-column>
      <el-table-column label="任务状态" align="center" prop="status" width="100px">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.taskerp_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="模版接取人员" align="center" prop="receiveTasksPerson" />
      <!--      <el-table-column label="驳回意见" align="center" prop="finalRejection" />-->
      <el-table-column label="模版素材" align="center" width="240px" prop="templateMaterial" />
      <el-table-column label="模版签字" align="center" prop="examineAttachment">
        <template slot-scope="scope">
          <image-preview v-if="/http/.test(scope.row.tempLeadSign)" :src="scope.row.tempLeadSign" style="width: 50%;height: 50%;"/>
          <span v-else>{{ scope.row.tempLeadSign }}</span>
        </template>
      </el-table-column>
      <el-table-column label="模版接取时间" align="center" prop="templateAcceptTime" />
      <el-table-column label="模版完成时间" align="center" prop="templateCompleteTime" />
      <el-table-column label="模版拼版接取人员" align="center" prop="make" />
      <el-table-column label="模版拼版状态" align="center" prop="makeStatus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.make_status" :value="scope.row.makeStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="模版拼版成品" align="center" prop="makeUrl"></el-table-column>
      <el-table-column label="模版拼版接取时间" align="center" prop="typesettingAcceptTime" />
      <el-table-column label="模版拼版完成时间" align="center" prop="typesettingCompleteTime" />
      <el-table-column label="美工接取人员" align="center" prop="artistAllocation" />
      <!--      <el-table-column label="驳回意见" align="center" prop="artisticFinalRejection" />-->
      <el-table-column label="美工成品" align="center" width="240px" prop="artisticFinishedProduct"></el-table-column>
      <el-table-column label="美工接取时间" align="center" prop="artworkAcceptTime" />
      <el-table-column label="美工完成时间" align="center" prop="artworkCompleteTime" />
      <el-table-column label="美工签字" align="center" prop="examineAttachment">
        <template slot-scope="scope">
          <image-preview v-if="/http/.test(scope.row.artLeadSign)" :src="scope.row.artLeadSign" style="width: 50%;height: 50%;"/>
          <span v-else>{{ scope.row.artLeadSign }}</span>
        </template>
      </el-table-column>
      <el-table-column label="sku接取人" align="center" prop="sku" />
      <el-table-column label="SKU成品链接" align="center" width="240px" prop="skuProductUrl" />
      <el-table-column label="SKU接取时间" align="center" prop="skuAcceptTime" />
      <el-table-column label="SKU完成时间" align="center" prop="skuCompleteTime" />
      <el-table-column label="SKU签字" align="center" prop="examineAttachment">
        <template slot-scope="scope">
          <image-preview v-if="/http/.test(scope.row.skuLeadSign)" :src="scope.row.skuLeadSign" style="width: 50%;height: 50%;"/>
          <span v-else>{{ scope.row.skuLeadSign }}</span>
        </template>
      </el-table-column>
      <!--      <el-table-column label="成品" align="center" width="90px">-->
      <!--        <template slot-scope="scope">-->
      <!--          <el-button type="text" icon="el-icon-download" @click="getdownloadUrl(scope.row)">成品下载</el-button>-->
      <!--        </template>-->
      <!--      </el-table-column>-->
      <el-table-column label="上架人员" align="center" prop="staff" />
      <el-table-column label="上架时间" align="center" prop="staffTime" />
      <el-table-column label="上架签字" align="center">
        <template slot-scope="scope">
          <image-preview v-if="scope.row.listingSign" :src="scope.row.listingSign" style="width: 50%;height: 50%;"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="150px" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-tooltip v-if="scope.row.staff == null && ((roles.includes('meigongzuzhang') && scope.row.type == 1) || (roles.includes('mobanzuzhang') && scope.row.type == 0) || roles.includes('admin') || roles.includes('zongjian') || roles.includes('meigongzhuguan') || roles.includes('administrator') || roles.includes('shangjiazhuli'))" class="item" effect="dark" placement="top">
            <div slot="content">
              <div v-if="scope.row.mainImages == 0">
                <div v-if="scope.row.type == 0">
                  <div v-if="scope.row.status < 6">模版未完成</div>
                  <div v-if="scope.row.status >= 6">模版已完成</div>
                  <div v-if="scope.row.makeStatus != 0 && scope.row.makeStatus != 4 && scope.row.makeStatus != null && scope.row.makeStatus != undefined">
                    <div v-if="scope.row.makeStatus != 3">拼版未完成</div>
                    <div v-if="scope.row.makeStatus == 3">拼版已完成</div>
                  </div>
                  <div v-if="scope.row.status < 11">美工未完成</div>
                  <div v-if="scope.row.status >= 11">美工已完成</div>
                  <div v-if="scope.row.status <= 12">SKU未完成</div>
                  <div v-if="scope.row.status >= 16">SKU已完成</div>
                </div>
                <div v-else>
                  <div v-if="scope.row.status < 11">美工未完成</div>
                  <div v-if="scope.row.status >= 11">美工已完成</div>
                  <div v-if="scope.row.status <= 12">SKU未完成</div>
                  <div v-if="scope.row.status >= 16">SKU已完成</div>
                </div>
              </div>
              <div v-else>
                <div v-if="scope.row.status < 6">模版未完成</div>
                <div v-if="scope.row.status >= 6">模版已完成</div>
                <div v-if="scope.row.makeStatus != 0 && scope.row.makeStatus != 4 && scope.row.makeStatus != null && scope.row.makeStatus != undefined">
                  <div v-if="scope.row.makeStatus != 3">拼版未完成</div>
                  <div v-if="scope.row.makeStatus == 3">拼版已完成</div>
                </div>
              </div>
            </div>

            <div v-if="scope.row.mainImages == 0">
              <div v-if="scope.row.type == 0">
                <div v-if="scope.row.makeStatus != 0 && scope.row.makeStatus != 4 && scope.row.makeStatus != null && scope.row.makeStatus != undefined">
                  <el-button type="text" icon="el-icon-edit" :disabled="!(scope.row.status >= 6 && scope.row.makeStatus == 3 && scope.row.status >= 11 && scope.row.status >= 16)" @click="updateStaffForms(scope.row)">上架</el-button>
                </div>
                <div v-else>
                  <el-button type="text" icon="el-icon-edit" :disabled="!(scope.row.status >= 6 && scope.row.status >= 11 && scope.row.status >= 16)" @click="updateStaffForms(scope.row)">上架</el-button>
                </div>
              </div>
              <div v-else>
                <el-button type="text" icon="el-icon-edit" :disabled="!(scope.row.status >= 11 && scope.row.status >= 16)" @click="updateStaffForms(scope.row)">上架</el-button>
              </div>
            </div>
            <div v-else>
              <div v-if="scope.row.makeStatus != 0 && scope.row.makeStatus != 4 && scope.row.makeStatus != null && scope.row.makeStatus != undefined">
                <el-button type="text" icon="el-icon-edit" :disabled="!(scope.row.status >= 6 && scope.row.makeStatus == 3)" @click="updateStaffForms(scope.row)">上架</el-button>
              </div>
              <div v-else>
                <el-button type="text" icon="el-icon-edit" :disabled="!(scope.row.status >= 6)" @click="updateStaffForms(scope.row)">上架</el-button>
              </div>
            </div>
          </el-tooltip>
          <div v-if="scope.row.userId == $store.getters.userId || (roles.includes('admin') || roles.includes('zongjian') || roles.includes('meigongzhuguan') || roles.includes('administrator')) || (roles.includes('mobanzuzhang') && scope.row.type == 0) || (roles.includes('meigongzuzhang'))">
            <!--            <el-button type="text" icon="el-icon-download" v-if="scope.row.status == 2" @click="handleExamineDownload(scope.row)">审核素材下载</el-button>-->
            <!--            <el-button type="text" icon="el-icon-download" v-if="scope.row.status == 8" @click="handleExamineDownload(scope.row)">审核素材下载</el-button>-->
            <el-button type="text" icon="el-icon-edit" v-if="(scope.row.status == 2 && (roles.includes('mobanzuzhang') || roles.includes('admin') || roles.includes('zongjian'))) || (scope.row.status == 8 && (roles.includes('meigongzuzhang') || roles.includes('admin') || roles.includes('zongjian'))) || (scope.row.status == 14 && (roles.includes('meigongzuzhang') || roles.includes('admin') || roles.includes('zongjian')))" @click="submitInspect(scope.row)">已检查</el-button> <!-- handleExamineUpdate -->
            <!--            <el-button type="text" icon="el-icon-edit" v-if="scope.row.status == 5" @click="getallocation(scope.row)">分配</el-button>-->
            <el-button type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)">修改</el-button>
            <el-button type="text" icon="el-icon-delete" @click="handleDelete(scope.row)">删除</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改任务erp对话框 -->
    <el-dialog title="分配" :visible.sync="fenpeiShow" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="是否通过" prop="title">
          <el-select v-model="form.status" placeholder="请选择" style="width: 100%;">
            <el-option v-for="item in [{ value: '5', label: '未分配'}, { value: '6', label: '美工'}, { value: '12', label: '拼版'}]" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleDesigningUpdate">确 定</el-button>
        <el-button @click="fenpeiShow = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 添加或修改任务erp对话框 -->
    <el-dialog title="审核" :visible.sync="examineShow" width="700px" append-to-body>
      <autograph v-if="examineShow" @confirm="handleConfirm" @clear="handleClear" @cancel="examineShow = false" @error="handleError"></autograph>
      <!--      <el-form ref="form" :model="form" :rules="rules" label-width="80px">-->
      <!--        <el-form-item label="是否通过" prop="title">-->
      <!--          <el-select v-model="form.didItPass" placeholder="请选择" style="width: 100%;">-->
      <!--            <el-option v-for="item in [{ value: '0', label: '驳回'}, { value: '1', label: '通过'}]" :key="item.value" :label="item.label" :value="item.value"></el-option>-->
      <!--          </el-select>-->
      <!--        </el-form-item>-->
      <!--        <el-form-item v-if="form.didItPass == 0 && form.status == 2" label="驳回意见" prop="describe">-->
      <!--          <el-input type="textarea" v-model="form.finalRejection" placeholder="请输入说明" style="width: 100%"></el-input>-->
      <!--        </el-form-item>-->
      <!--        <el-form-item v-if="form.didItPass == 0 && form.status == 8" label="驳回意见" prop="describe">-->
      <!--          <el-input type="textarea" v-model="form.artisticFinalRejection" placeholder="请输入说明" style="width: 100%"></el-input>-->
      <!--        </el-form-item>-->
      <!--      </el-form>-->
      <!--      <div slot="footer" class="dialog-footer">-->
      <!--        <el-button type="primary" @click="submitExamineForms">确 定</el-button>-->
      <!--        <el-button @click="examineShow = false">取 消</el-button>-->
      <!--      </div>-->
    </el-dialog>

    <!-- 添加或修改任务erp对话框 -->
    <el-dialog title="上架" :visible.sync="staffShow" width="700px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="上架时间" prop="title">
          <el-date-picker v-model="form.staffTime" type="date" placeholder="选择日期" style="width: 100%;"></el-date-picker>
        </el-form-item>
        <autograph v-if="staffShow" @confirm="submitStaffForms" @clear="handleClear" @cancel="staffShow = false" @error="handleError"></autograph>
      </el-form>
<!--      <div slot="footer" class="dialog-footer">-->
<!--        <el-button type="primary" @click="submitStaffForms">确 定</el-button>-->
<!--        <el-button @click="staffShow = false">取 消</el-button>-->
<!--      </div>-->
    </el-dialog>

    <!-- 添加或修改任务erp对话框 -->
    <el-dialog :title="title" v-dialog-move :visible.sync="open" width="500px" append-to-body style="margin-bottom: 35px;" @paste.native="handlerPaste">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <!--        <el-form-item label="标题" prop="title">-->
        <!--          <el-input v-model="form.title" placeholder="请输入标题" clearable style="width: 100%"/>-->
        <!--        </el-form-item>-->
        <el-form-item label="日期" prop="title">
          <el-date-picker v-model="form.title" type="date" placeholder="选择日期" style="width: 100%;"></el-date-picker>
        </el-form-item>
        <el-form-item label="类别" prop="type">
          <el-select v-model="form.type" placeholder="请选择类别" clearable style="width: 100%;">
            <el-option v-for="dict in dict.type.taskerp_type" :key="dict.value" :label="dict.label" :value="dict.value"/>
          </el-select>
        </el-form-item>
        <el-form-item label="店铺" prop="shop">
          <el-select v-model="form.shop" placeholder="请输入店铺" filterable clearable style="width: 100%;">
            <el-option v-for="(item, index) in ['乐艺贴饰', '始发旗舰店', '济南中呈商贸有限公司', '九变定制旗舰店', '九变定制文具', '搜途办公专营店', '哲众旗舰店', 'jnjb2008', '派依倍旗舰店', '智詹官方旗舰店', '锦玉轩家纺家具官方旗舰店', '中奥数码电器', '迪士普数码电器官方旗舰店', '素锦留旗舰店', '起辰', '星耀创意贴饰', '翔启扬旗舰店', '丝乐爽旗舰店', '雨恋冰纯旗舰店', '铎金办公专营店', '智呈旗舰店', '世格创意贴饰', '呈讯旗舰店', '华鲁搜途旗舰店', '智宏汇旗舰店', '展迪优文具馆', '中艺创意家居', '董东东2013', '广格宏家纺家具官方旗舰店', '美格鸿旗舰店', '格莱美海报工厂', '九鼎铎金官方旗舰店', '知迅唐办公用品旗舰店', '中展航标识', '中弘图韵官方旗舰店', '宝菁旗舰店', '中奥晋呈旗舰店', '中弘海报2', '屹呈旗舰店', '九鼎铎金旗舰店', '益讯旗舰店', '中慧达旗舰店', '中利呈旗舰店', '画萌文教用具旗舰店']"
                       :key="index" :label="item" :value="item"/>
          </el-select>
        </el-form-item>
        <el-form-item label="是否加急" prop="emergency">
          <el-select v-model="form.emergency" placeholder="请选择是否加急" clearable style="width: 100%;">
            <el-option v-for="dict in dict.type.emergency" :key="dict.value" :label="dict.label" :value="dict.value"/>
          </el-select>
        </el-form-item>
        <el-form-item label="产品编码" prop="productCode">
          <el-input v-model="form.productCode" @blur="validateProductCode" placeholder="请输入产品编码" style="width: 100%"></el-input>
        </el-form-item>
        <el-form-item label="参考链接1" prop="referenceLink">
          <el-input v-model="form.referenceLink" placeholder="请输入参考链接" style="width: 100%"></el-input>
        </el-form-item>
        <el-form-item label="参考链接2" prop="referenceLinkOne">
          <el-input v-model="form.referenceLinkOne" @blur="validateReferenceLinkOne" placeholder="请输入参考链接" style="width: 100%"></el-input>
        </el-form-item>
        <el-form-item label="参考链接3" prop="referenceLinkTwo">
          <el-input v-model="form.referenceLinkTwo" @blur="validateReferenceLinkTwo" placeholder="请输入参考链接" style="width: 100%"></el-input>
        </el-form-item>
        <el-form-item label="模版数量" prop="templatesNum">
          <el-input v-model="form.templatesNum" placeholder="请输入模版数量" style="width: 100%"></el-input>
        </el-form-item>
        <el-form-item label="参考图" prop="attachment">
          <el-upload
            ref="upload"
            accept=".png, .jpg, .jpeg, .psd, .ai, .rar, .zip, .gz"
            :multiple="true"
            :headers="upload.headers"
            action="#"
            :disabled="upload.isUploading"
            :action="upload.url"
            :file-list="fileList"
            :on-remove="handleFileRemove"
            :on-change="handleFileChange"
            :on-success="handleUploadSuccess"
            :auto-upload="false"
            drag
          >
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            <div class="el-upload__tip text-center" slot="tip">
              <span>仅允许导入.png, .jpg, .jpeg, .psd, .ai, .rar, .zip, .gz格式文件。</span>
            </div>
          </el-upload>
        </el-form-item>
        <el-form-item label="模版要求" prop="templateReq">
          <el-input type="textarea" v-model="form.templateReq" placeholder="请输入模版要求" style="width: 100%"></el-input>
        </el-form-item>
        <el-form-item label="尺寸要求" prop="sizeReq">
          <el-input type="textarea" v-model="form.sizeReq" placeholder="请输入尺寸要求" style="width: 100%"></el-input>
        </el-form-item>
        <el-form-item label="主图详情要求" prop="mainImgReq">
          <el-input type="textarea" v-model="form.mainImgReq" placeholder="请输入主图详情要求" style="width: 100%"></el-input>
        </el-form-item>
        <el-form-item v-if="form.type == 0" label="是否需要主图" prop="mainImages">
          <el-select v-model="form.mainImages" placeholder="请选择" clearable style="width: 100%;">
            <el-option v-for="(item, index) in ['是', '否']" :key="index" :label="item" :value="index"/>
          </el-select>
        </el-form-item>
        <el-form-item label="类目要求" prop="categoryReq">
          <el-input type="textarea" v-model="form.categoryReq" placeholder="请输入类目要求" style="width: 100%"></el-input>
        </el-form-item>
        <el-form-item label="类型" prop="complexity">
          <el-select v-model="form.complexity" placeholder="请选择类型" clearable style="width: 100%;">
            <el-option v-for="dict in dict.type.complexity" :key="dict.value" :label="dict.label" :value="dict.value"/>
          </el-select>
        </el-form-item>
        <el-form-item v-if="roles.includes('admin') || roles.includes('zongjian') || roles.includes('meigongzhuguan') || roles.includes('administrator') || roles.includes('mobanzuzhang') || roles.includes('meigongzuzhang')" label="是否分配" prop="userRadio  ">
          <el-select v-model="userRadio" placeholder="请选择" filterable style="width: 100%">
            <el-option v-for="(item, index) in ['否','是']" :key="index" :label="item" :value="index"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="userRadio == 1" label="分配人员" prop="userId">
          <el-select v-model="userId" placeholder="请选择分配人员" filterable clearable style="width: 100%;">
            <el-option v-for="(item, index) in receivedList[form.type]" :key="index" :label="item.state+'-'+item.name" :value="index"/>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForms">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 添加或修改任务erp对话框 -->
    <el-dialog title="" :visible.sync="transferTaskShow" width="850px" append-to-body>
      <el-table ref="singleTable" :data="tableData" style="width: 100%">
        <el-table-column label="产品编码" fixed align="center" prop="productCode" />
        <el-table-column label="模版人员" width="160px">
          <template slot-scope="scope">
            <el-select v-model="scope.row.receiveTasksPerson" :disabled="scope.row.status != 1" filterable placeholder="请选择">
              <el-option v-for="item in receivedTenList" :key="item.userId" :label="item.state" :value="item.userId+''"></el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="美工人员" width="160px">
          <template slot-scope="scope">
            <el-select v-model="scope.row.artistAllocation" :disabled="scope.row.status != 7" filterable placeholder="请选择">
              <el-option v-for="item in receivedElevenList" :key="item.userId" :label="item.state" :value="item.userId"></el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="SKU人员" width="160px">
          <template slot-scope="scope">
            <el-select v-model="scope.row.sku" :disabled="scope.row.status != 13" filterable placeholder="请选择">
              <el-option v-for="item in receivedThirteenList" :key="item.userId" :label="item.state" :value="item.userId+''"></el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="拼版人员" width="160px">
          <template slot-scope="scope">
            <el-select v-model="scope.row.make" :disabled="scope.row.makeStatus != 2" filterable placeholder="请选择">
              <el-option v-for="item in receivedTwelveList" :key="item.userId" :label="item.state" :value="item.userId+''"></el-option>
            </el-select>
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitTransferTaskForms">确 定</el-button>
        <el-button @click="transferTaskShow = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 添加或修改任务erp对话框 -->
    <el-dialog title="" :visible.sync="assignTasksShow" width="850px" append-to-body>
      <el-table ref="singleTable" :data="assignTasksList" style="width: 100%">
        <el-table-column label="产品编码" fixed align="center" prop="productCode" />
        <el-table-column label="类别" align="center" prop="type">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.taskerp_type" :value="scope.row.type"/>
          </template>
        </el-table-column>
        <el-table-column label="模版人员" width="160px">
          <template slot-scope="scope">
            <el-select v-model="scope.row.receiveTasksPerson" :disabled="scope.row.status != 0 && scope.$index != (assignTasksList.length - 1)" @change="assignTasksChange(scope.row.receiveTasksPerson, 0, scope.$index != (assignTasksList.length - 1))" filterable placeholder="请选择">
              <el-option v-for="item in receivedTenList" :key="item.userId" :label="item.state" :value="item.userId+''"></el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="美工人员" width="160px">
          <template slot-scope="scope">
            <el-select v-model="scope.row.artistAllocation" :disabled="scope.row.status != 6 && scope.$index != (assignTasksList.length - 1)" @change="assignTasksChange(scope.row.artistAllocation, 1, scope.$index != (assignTasksList.length - 1))" filterable placeholder="请选择">
              <el-option v-for="item in receivedElevenList" :key="item.userId" :label="item.state" :value="item.userId"></el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="SKU人员" width="160px">
          <template slot-scope="scope">
            <el-select v-model="scope.row.sku" :disabled="scope.row.status != 12 && scope.$index != (assignTasksList.length - 1)" @change="assignTasksChange(scope.row.sku, 2, scope.$index != (assignTasksList.length - 1))" filterable placeholder="请选择">
              <el-option v-for="item in receivedThirteenList" :key="item.userId" :label="item.state" :value="item.userId+''"></el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="拼版人员" width="160px">
          <template slot-scope="scope">
            <el-select v-model="scope.row.make" :disabled="scope.row.makeStatus != 1 && scope.$index != (assignTasksList.length - 1)" @change="assignTasksChange(scope.row.make, 3, scope.$index != (assignTasksList.length - 1))" filterable placeholder="请选择">
              <el-option v-for="item in receivedTwelveList" :key="item.userId" :label="item.state" :value="item.userId+''"></el-option>
            </el-select>
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitAssignTasksForms">确 定</el-button>
        <el-button @click="assignTasksShow = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  exportExcel,
  getTaskerp,
  listTaskerp,
  updateTaskerp,
  delTaskerp,
  addTaskerp,
  getUserIdList,
  getReceiveTasksPersonList,
  getMakeUpList,
  getArtistAllocationList,
  getDoesItExist,
  getAssignTasksList,
  oldFileName
} from "@/api/business/taskerp.js";
import { listReceived, selectUserRole } from "@/api/business/received";
import autograph from "@/components/autograph/autograph.vue"
import ResizeMixin from "@/layout/mixin/ResizeHandler";
import {getToken} from "@/utils/auth";
import {parseTime} from "@/utils/ruize";
import axios from 'axios'

export default {
  dicts: ['complexity', 'taskerp_type', 'emergency', 'taskerp_status', 'make_status'],
  name: "Taskerp",
  components: {autograph},
  mixins: [ResizeMixin],
  data() {
    const validateReferenceLink = (rule, value, callback) => {
      this.checkReferenceLink(value).then(isUnique => {
        if (!isUnique) {
          callback(new Error('参考链接1已存在'));
        } else {
          callback();
        }
      });
    };
    return {
      // 表格高度
      tableHeight: 0,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 任务erp表格数据
      taskerpList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      fenpeiShow: false,
      examineShow: false,
      staffShow: false,
      timeRanges: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        title: null,
        type: null,
        state: null
      },
      // 表单参数
      form: {},
      userRadio: 0,
      userId: null,
      // 表单校验
      rules: {
        type: [
          { required: true, message: '请输入类别', trigger: 'blur' },
        ],
        shop: [
          { required: true, message: '请输入店铺', trigger: 'blur' },
        ],
        productCode: [
          { required: true, message: '请输入产品编码', trigger: 'blur' },
        ],
        templatesNum: [
          { required: true, message: '请输入模版数量', trigger: 'blur' },
        ],
        templateReq: [
          { required: true, message: '请输入模版要求', trigger: 'blur' },
        ],
        sizeReq: [
          { required: true, message: '请输入尺寸要求', trigger: 'blur' },
        ],
        mainImgReq: [
          { required: true, message: '请输入主图详情要求', trigger: 'blur' },
        ],
        mainImages: [
          { required: true, message: '请选择是否需要主图', trigger: 'blur' },
        ],
        categoryReq: [
          { required: true, message: '请输入类目要求', trigger: 'blur' },
        ],
        complexity: [
          { required: true, message: '请输入类型', trigger: 'blur' },
        ],
        referenceLink: [
          { validator: validateReferenceLink, trigger: 'blur' }
        ],
      },
      // 客服绩效导入参数
      upload: {
        isUploading: false,
        // 弹出层标题（客服绩效导入）
        title: "",
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/common/oldName"
      },
      fileList: [],
      userIdList: [],
      receiveTasksPersonList: [],
      makeUpList: [],
      artistAllocationList: [],
      receivedList: [],
      roles: "",
      transferTaskShow: false,
      assignTasksShow: false,
      receivedTenList: [],
      receivedElevenList: [],
      receivedThirteenList: [],
      receivedTwelveList: [],
      tableData: [],
      assignTasksList: [],
    };
  },
  created() {
    this.roles = this.$store.getters.roles.join();
    if (this.roles.includes('mobanzuzhang')){
      this.queryParams.type = 0
      this.queryParams.statusList = [0]
      this.queryParams.makeStatus = 2
    }else if (this.roles.includes('meigongzuzhang')){
      this.queryParams.type = 1
      this.queryParams.statusList = [0,6]
    }
    this.getList();
    this.getlistReceived();
    this.getUserIdList()
    this.getMakeUpList()
    this.getReceiveTasksPersonList()
    this.getArtistAllocationList()
  },
  methods: {
    async transferTask(){
      this.tableData = []
      await selectUserRole().then(r => {
        const mobanzuzhang = r.data.filter(row => row.role_id == "35");
        const meigongzuzhang = r.data.filter(row => row.role_id == "36");
        listReceived({ postList: [ 10 ], pageSize: 1000 }).then(res => {
          this.receivedTenList = [...mobanzuzhang, ...res.rows]
        })
        listReceived({ postList: [ 11 ], pageSize: 1000 }).then(res => {
          this.receivedElevenList = [...meigongzuzhang, ...res.rows]
        })
        listReceived({ postList: [ 12 ], pageSize: 1000 }).then(res => {
          this.receivedTwelveList = [...mobanzuzhang, ...res.rows]
        })
        listReceived({ postList: [ 13 ], pageSize: 1000 }).then(res => {
          this.receivedThirteenList = [...meigongzuzhang, ...res.rows]
        })
      })
      this.tableData = []
      getAssignTasksList({id: this.ids.join()}).then(response => {
        response.data.map(i => {
          if(i.status == 1){
            this.tableData.push({ ...i })
          }else if(i.status == 7){
            this.tableData.push({ ...i })
          }else if(i.status == 13){
            this.tableData.push({ ...i })
          }else if(i.makeStatus == 2){
            this.tableData.push({ ...i })
          }
        })
      });
      this.transferTaskShow = true
    },
    async assignTasks(){
      this.assignTasksList = []
      await listReceived({ postList: [ 10 ], pageSize: 1000 }).then(res => {
        this.receivedTenList = res.rows
      })
      await listReceived({ postList: [ 11 ], pageSize: 1000 }).then(res => {
        this.receivedElevenList = res.rows
      })
      await listReceived({ postList: [ 12 ], pageSize: 1000 }).then(res => {
        this.receivedTwelveList = res.rows
      })
      await listReceived({ postList: [ 13 ], pageSize: 1000 }).then(res => {
        this.receivedThirteenList = res.rows
      })
      getAssignTasksList({id: this.ids.join()}).then(response => {
        response.data.map(i => {
          if(i.status == 0){
            this.assignTasksList.push({ ...i })
          }else if(i.status == 6){
            this.assignTasksList.push({ ...i })
          }else if(i.status == 12){
            this.assignTasksList.push({ ...i })
          }else if(i.makeStatus == 1){
            this.assignTasksList.push({ ...i })
          }
        })
        this.assignTasksList.push({})
        this.assignTasksShow = true
      });
    },
    submitTransferTaskForms(){
      let list = [];
      this.tableData.map(i => {
        if(i.status == 1){
          list.push({ id: i.id, receiveTasksPerson: i.receiveTasksPerson })
        }else if(i.status == 7){
          list.push({ id: i.id, artistAllocation: i.artistAllocation })
        }else if(i.status == 13){
          list.push({ id: i.id, sku: i.sku })
        }else if(i.makeStatus == 2){
          list.push({ id: i.id, make: i.make })
        }
      })
      Promise.all(
        list.map(i =>
          updateTaskerp(i)
        )
      ).then(results => {
        console.log(results)
        // 所有删除操作成功完成
        this.tableData = []
        this.$message({ message: '任务转交完成！', type: 'success' });
        this.getList()
        this.transferTaskShow = false
      }).catch(error => {
        // 处理错误
        console.log(error)
        this.$message.error('任务转交失败，请联系管理员');
      });
    },
    assignTasksChange(value, index, type){
      console.log(value, index, type)
      if (!type){
        if (index == 0){
          this.assignTasksList.map((item, index) => {
            if (index == this.assignTasksList.length - 1){
              return
            }
            if (!(item.status != 0)){
              item.receiveTasksPerson = value
            }
          })
        }else if (index == 1){
          this.assignTasksList.map((item, index) => {
            if (index == this.assignTasksList.length - 1){
              return
            }
            if (!(item.status != 6)){
              item.artistAllocation = value
            }
          })
        }else if (index == 2){
          this.assignTasksList.map((item, index) => {
            if (index == this.assignTasksList.length - 1){
              return
            }
            if (!(item.status != 12)){
              item.sku = value
            }
          })
        }else if (index == 3){
          this.assignTasksList.map((item, index) => {
            if (index == this.assignTasksList.length - 1){
              return
            }
            if (!(item.makeStatus != 1)){
              item.make = value
            }
          })
        }
      }
    },
    submitAssignTasksForms(){
      let list = [];
      this.assignTasksList.map(i => {
        if(i.status == 0){
          list.push({ id: i.id, receiveTasksPerson: i.receiveTasksPerson, status: 1, templateAcceptTime: parseTime(new Date()) })
        }else if(i.status == 6){
          list.push({ id: i.id, artistAllocation: i.artistAllocation, status: 7, artworkAcceptTime: parseTime(new Date()) })
        }else if(i.status == 12){
          list.push({ id: i.id, sku: i.sku, status: 13, skuAcceptTime: parseTime(new Date()) })
        }else if(i.makeStatus == 1){
          list.push({ id: i.id, make: i.make, makeStatus: 2, typesettingAcceptTime: parseTime(new Date()) })
        }
      })
      Promise.all(
        list.map(i =>
          updateTaskerp(i)
        )
      ).then(results => {
        // 所有删除操作成功完成
        this.assignTasksList = []
        this.$message({ message: '任务分配完成！', type: 'success' });
        this.assignTasksShow = false
        this.getList()
      }).catch(error => {
        // 处理错误
        console.log(error)
        this.$message.error('任务分配失败，请联系管理员');
      });
    },

    handlerPaste(e){
      // 处理用户频繁粘贴操作
      let now = new Date().getTime()
      if(now - this.timeStep < 500){
        this.$message.warning('粘贴速度太频繁！请稍后再试');
        return
      }
      this.timeStep = now
      var clipboardData = e.clipboardData; // IE
      if (!clipboardData) {//chrome
        clipboardData = e.originalEvent.clipboardData;
      }
      var items='';
      items = (e.clipboardData || window.clipboardData).items;
      let file = null;
      if (!items || items.length === 0) {
        this.$message.error('当前浏览器不支持粘贴本地图片，请打开图片复制后再粘贴！');
        return;
      }
      // 搜索剪切板items
      for (let i = 0; i < items.length; i++) {
        file = items[i].getAsFile();
      }
      // 对复制黏贴的类型进行判断，若是非文件类型，比如复制黏贴的文字，则不会调用上传文件的函数
      if(file){
        // 生成预览图
        this.$refs.upload.handleStart(file);
      }
    },
    getlistReceived() {
      listReceived({ pageSize: 1000 }).then(response => {
        this.receivedList[0] = response.rows.filter(row => row.postId === 10).map(row => { return { ...row, name: "模版" } });
        this.receivedList[1] = response.rows.filter(row => row.postId === 11).map(row => { return { ...row, name: "美工" } });
      });
    },
    getUserIdList(){
      getUserIdList().then(res => {
        this.userIdList = res.data
      })
    },
    getReceiveTasksPersonList(){
      getReceiveTasksPersonList().then(res => {
        this.receiveTasksPersonList = res.data
      })
    },
    getMakeUpList(){
      getMakeUpList().then(res => {
        this.makeUpList = res.data
      })
    },
    getArtistAllocationList(){
      getArtistAllocationList().then(res => {
        this.artistAllocationList = res.data
      })
    },
    validateProductCode(){
      this.checkProductCode(this.form.productCode, "1").then(isUnique => {
        if (!isUnique) {
          alert('产品编码已存在，是否继续填写？');
        }
      });
    },
    validateReferenceLinkOne(){
      this.checkProductCode(this.form.referenceLinkOne, "2").then(isUnique => {
        if (!isUnique) {
          alert('参考链接2已存在，是否继续填写？');
        }
      });
    },
    validateReferenceLinkTwo(){
      this.checkProductCode(this.form.referenceLinkTwo, "3").then(isUnique => {
        if (!isUnique) {
          alert('参考链接3已存在，是否继续填写？');
        }
      });
    },
    checkProductCode(value, type) {
      return new Promise(resolve => {
        if (value){
          let query = {}
          if (type == "1"){
            query = {productCode: value.replace(/\D/g, ''), id: this.form.id}
          }else if (type == "2"){
            query = {referenceLinkOne: value, id: this.form.id}
          }else if (type == "3"){
            query = {referenceLinkTwo: value, id: this.form.id}
          }
          getDoesItExist(query).then(response => {
            resolve(response.data.length  == 0);
          });
        }else {
          resolve(true);
        }
      });
    },
    checkReferenceLink(value) {
      return new Promise(resolve => {
        if (value){
          getDoesItExist({referenceLink: value, id: this.form.id}).then(response => {
            resolve(response.data.length  == 0);
          });
        }else {
          resolve(true);
        }
      });
    },
    copyUrl(url) {
      // 检测用户代理字符串
      const userAgent = navigator.userAgent;
      // 判断是否为IE浏览器
      const isIE = userAgent.indexOf('MSIE ') > -1 || userAgent.indexOf('Trident/') > -1;
      // 判断是否为Edge浏览器
      const isEdge = userAgent.indexOf('Edge/') > -1;
      // 判断是否为Firefox浏览器
      const isFirefox = userAgent.indexOf('Firefox/') > -1;
      // 根据不同浏览器执行不同的复制策略
      if (isIE) {
        // IE浏览器使用旧的方法
        this.copyTextToClipboardIE(url);
      } else if (isEdge || isFirefox) {
        // Edge和Firefox浏览器可能需要权限，尝试使用现代API
        this.copyTextToClipboardModern(url);
      } else {
        // 其他浏览器默认使用现代API
        this.copyTextToClipboardModern(url);
      }
    },
    copyTextToClipboardIE(url) {
      const textArea = document.createElement('textarea');
      textArea.value = url;
      document.body.appendChild(textArea);
      textArea.select();
      try {
        document.execCommand('copy');
        this.$message('文本已复制到剪贴板');
      } catch (err) {
        this.$message.error("无法复制文本");
      }
      document.body.removeChild(textArea);
    },
    copyTextToClipboardModern(url) {
      if (navigator.clipboard) {
        navigator.clipboard.writeText(url).then(() => {
          this.$message('文本已复制到剪贴板');
        }).catch(err => {
          this.$message.error("无法复制文本");
        });
      } else {
        this.copyTextToClipboardIE(url); // 如果现代API不可用，回退到IE的方法
      }
    },
    toUrl(url){
      window.open(url, '_blank');
    },
    /** 多个文件一起提交*/
    handleFileChange(file, fileList) {
      this.fileList = fileList;
    },
    /** 源文件上传列表删除事件*/
    handleFileRemove() {
      // 源文件删除，同时将hash值清空
      this.form.referenceImage = ''
    },
    handleUploadSuccess(res, file) {
      if (res.code === 200) {
        let list = []
        let fileList = JSON.parse(JSON.stringify(this.fileList))
        if (fileList[fileList.length - 1].response.originalFilename == res.originalFilename){
          fileList.map(i => {
            list.push(i.response.fileName)
          })
          this.form.referenceImage = list.join()
          this.submitForm()
        }
      } else {
        this.$modal.closeLoading();
        this.$modal.msgError(res.msg);
        this.$refs.upload.handleRemove(file);
      }
    },
    /** 查询任务erp列表 */
    getList() {
      this.loading = true;
      listTaskerp(this.queryParams).then(response => {
        this.taskerpList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.$refs.upload.clearFiles();
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        title: null,
        type: null,
        templateReq: null,
        sizeReq: null,
        mainImgReq: null,
        categoryReq: null,
        attachment: null,
        complexity: null,
        didItPass: null,
        finalRejection: null,
        templateMaterial: null,
        status: null,
        receiveTasksPerson: null,
        artistAllocation: null,
        artisticFinishedProduct: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        state: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.queryParams.type = null;
      this.queryParams.statusList = null
      this.queryParams.makeStatus = null
      if (this.timeRanges.length == 2){
        this.queryParams.beginTime = parseTime(this.timeRanges[0], "{y}-{m}-{d}")
        this.queryParams.endTime = parseTime(this.timeRanges[1], "{y}-{m}-{d}")
      }
      if (this.queryParams.statusMap == 0){
        this.queryParams.type = 0;
        this.queryParams.statusList = [0]
      }else if (this.queryParams.statusMap == 1){
        this.queryParams.statusList = [1]
      }else if (this.queryParams.statusMap == 2){
        this.queryParams.statusList = [2]
      }else if (this.queryParams.statusMap == 3){
        this.queryParams.type = 1;
        this.queryParams.statusList = [0,6]
      }else if (this.queryParams.statusMap == 4){
        this.queryParams.statusList = [7]
      }else if (this.queryParams.statusMap == 5){
        this.queryParams.statusList = [8]
      }else if (this.queryParams.statusMap == 6){
        this.queryParams.makeStatus = 1
      }else if (this.queryParams.statusMap == 7){
        this.queryParams.makeStatus = 2
      }else if (this.queryParams.statusMap == 8){
        this.queryParams.statusList = [12]
      }else if (this.queryParams.statusMap == 9){
        this.queryParams.statusList = [13]
      }else if (this.queryParams.statusMap == 10){
        this.queryParams.statusList = [14]
      }
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        title: null,
        type: null,
        statusMap: null,
        staff: null,
        state: null
      }
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.fileList = []
      this.open = true;
      this.userRadio = 0;
      this.userId  = null
      this.$set(this.form, "title", new Date())
      this.$set(this.form, "emergency", "1")
      this.$set(this.form, "mainImages", 0)
      this.title = "添加任务erp";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      this.fileList = []
      this.userRadio = 0;
      this.userId  = null
      getTaskerp(id).then(response => {
        this.form = response.data;
        if (new Date(this.form.title) == "Invalid Date"){
          this.form.title = null
        }
        this.open = true;
        this.title = "修改任务erp";
      });
    },
    /** 修改按钮操作 */
    updateStaffForms(row) {
      this.reset();
      const id = row.id || this.ids
      getTaskerp(id).then(response => {
        this.form = response.data;
        this.form.staff = this.$store.getters.userId
        this.staffShow = true;
      });
    },
    getallocation(row){
      getTaskerp(row.id).then(response => {
        this.form = response.data;
        this.fenpeiShow = true
      });
    },
    handleDesigningUpdate() {
      this.loading = true;
      updateTaskerp(this.form).then(response => {
        this.$modal.msgSuccess("操作成功");
        this.fenpeiShow = false
        this.getList();
      });
    },
    handleExamineDownload(row) {
      let urlString = ""
      const _this = this
      if (row.status == 2){
        urlString = row.examineAttachment;
      }else {
        urlString = row.artisticExamineAttachment;
      }
      // 假设URLs是以逗号分隔的
      const urls = urlString.split(','); // 根据实际情况，可能需要使用不同的分隔符
      urls.forEach(url => {
        axios({
          url: process.env.VUE_APP_BASE_API + url.trim(), // trim()用于移除字符串两端的空白字符
          method: 'GET',
          responseType: 'blob', // 重要：需要设置响应类型为blob
        }).then(response => {
          // 假设每个URL对应的文件名可以通过某种方式获得，这里我们使用url作为文件名
          const fileName = this.getBaseName(url.split('/').pop().split('?')[0]);
          const fileUrl = window.URL.createObjectURL(new Blob([response.data]));
          const link = document.createElement('a');
          link.href = fileUrl;
          link.setAttribute('download', fileName); // 或者你想要的名字
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link); // 下载后移除元素
          window.URL.revokeObjectURL(fileUrl); // 释放URL对象
        }).catch(error => {
          console.error('下载失败:', error);
        });
      });
    },
    downloadUrl(urlString) {
      // 假设URLs是以逗号分隔的
      const urls = urlString.split(','); // 根据实际情况，可能需要使用不同的分隔符
      urls.forEach(url => {
        // 构建完整的下载URL
        const downloadUrl = process.env.VUE_APP_BASE_API + url.trim();
        // 创建一个临时的a标签用于下载
        const a = document.createElement('a');
        a.href = downloadUrl;
        a.download = ''; // 可以根据需要设置下载文件名
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
      });
    },
    getdownloadUrl(row){
      let str = '';
      if (row.templateMaterial !== '' && row.templateMaterial !== null && row.templateMaterial !== undefined) {
        str += (str.length > 0 ? ',' : '') + row.templateMaterial;
      }
      if (row.makeUrl !== '' && row.makeUrl !== null && row.makeUrl !== undefined) {
        str += (str.length > 0 ? ',' : '') + row.makeUrl;
      }
      if (row.artisticFinishedProduct !== '' && row.artisticFinishedProduct !== null && row.artisticFinishedProduct !== undefined) {
        str += (str.length > 0 ? ',' : '') + row.artisticFinishedProduct;
      }
      if (str.length == 0){
        this.$message.error('没有成品！');
      }else {
        this.downloadUrl(str)
      }
    },
    getBaseName(fileName) {
      const underscoreIndex = fileName.indexOf('_');
      const houzui = fileName.split('.')[1]
      if (underscoreIndex !== -1) {
        return fileName.substring(0, underscoreIndex) + '.' + houzui;
      }
      return fileName + '.' + houzui; // 如果没有找到'_'，则返回整个文件名
    },
    getFileNameFromUrl(url) {
      return url.substring(url.lastIndexOf('/') + 1);
    },
    submitForms(){
      if (this.fileList.length == 0){
        this.submitForm()
      }else {
        this.$refs.upload.submit();
      }
    },
    handleClear() {
      this.$message('签名已清除!');
    },
    handleError(error) {
      this.$message.error('发生错误:'+error);
    },
    /** 修改按钮操作 */
    handleExamineUpdate(row) {
      getTaskerp(row.id).then(response => {
        this.form = response.data;
        this.examineShow = true
      });
    },
    handleConfirm(blob) {
      // 处理获得的Blob对象
      const formData = new FormData()
      formData.append('file', blob, new Date().getTime()+'_signature.png')
      oldFileName(formData).then(res => {
        console.log(res)
        this.submitExamineForms(res.fileName)
      })
    },
    submitExamineForms(url){
      console.log(this.form)
      if(this.roles.includes('admin') || this.roles.includes('zongjian')){
        if (this.form.type == 0 && this.form.mainImages == 0){
          this.form.status = 4
        }else if (this.form.status == 2){
          this.form.status = 6
        }else if (this.form.status == 8){
          this.form.status = 12
          this.form.artLeadSign = url
        }else if (this.form.status == 14){
          this.form.status = 16
          this.form.skuLeadSign = url
        }
      }else if (this.roles.includes('mobanzuzhang')){
        this.form.status = 6
        this.form.tempLeadSign = url
      }else if (this.roles.includes('meigongzuzhang')){
        if (this.form.status == 8){
          this.form.status = 12
          this.form.artLeadSign = url
        }else if (this.form.status == 14){
          this.form.status = 16
          this.form.skuLeadSign = url
        }
      }
      updateTaskerp(this.form).then(response => {
        this.$modal.msgSuccess("审核成功");
        this.examineShow = false;
        this.getList();
      });
    },
    submitInspect(row){
      const loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      getTaskerp(row.id).then(response => {
        this.form = response.data;
        if(this.roles.includes('admin') || this.roles.includes('zongjian')){
          if (this.form.type == 0 && this.form.mainImages == 1){
            this.form.status = 4
            this.form.tempLeadSign = this.$store.getters.nickName
          }else if (this.form.status == 2){
            this.form.status = 6
            this.form.tempLeadSign = this.$store.getters.nickName
          }else if (this.form.status == 8){
            this.form.status = 12
            this.form.artLeadSign = this.$store.getters.nickName
          }else if (this.form.status == 14){
            this.form.status = 16
            this.form.skuLeadSign = this.$store.getters.nickName
          }
        }else if (this.roles.includes('mobanzuzhang')){
          if (this.form.type == 0 && this.form.mainImages == 1){
            this.form.status = 4
            this.form.tempLeadSign = this.$store.getters.nickName
          }else if (this.form.status == 2){
            this.form.status = 6
            this.form.tempLeadSign = this.$store.getters.nickName
          }
        }else if (this.roles.includes('meigongzuzhang')){
          if (this.form.status == 8){
            this.form.status = 12
            this.form.artLeadSign = this.$store.getters.nickName
          }else if (this.form.status == 14){
            this.form.status = 16
            this.form.skuLeadSign = this.$store.getters.nickName
          }
        }
        updateTaskerp({ id: this.form.id, status: this.form.status, artLeadSign: this.form.artLeadSign, tempLeadSign: this.form.tempLeadSign, skuLeadSign: this.form.skuLeadSign }).then(response => {
          this.$modal.msgSuccess("审核成功");
          loading.close();
          this.getList();
        });
      });
    },
    submitStaffForms(blob){
      // 处理获得的Blob对象
      const formData = new FormData()
      formData.append('file', blob, new Date().getTime()+'_signature.png')
      oldFileName(formData).then(res => {
        this.form.staffTime = parseTime(this.form.staffTime, "{y}-{m}-{d}")
        this.form.listingSign = res.fileName
        updateTaskerp(this.form).then(response => {
          this.$modal.msgSuccess("操作成功");
          this.staffShow = false;
          this.getList();
        });
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.userRadio == 1){
            const data = this.receivedList[this.form.type][this.userId]
            console.log(data)
            if (data.postId == 10){
              this.form.receiveTasksPerson = data.userId
              this.form.status = 1
              this.form.templateAcceptTime = parseTime(new Date())
            }else if(data.postId == 11){
              this.form.artistAllocation = data.userId
              this.form.status = 7
              this.form.artworkAcceptTime = parseTime(new Date())
            }
          }
          if (this.form.type == 1){
            this.form.mainImages == 1
          }
          if (this.form.id != null) {
            this.form.title = parseTime(this.form.title, "{y}-{m}-{d}")
            updateTaskerp(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            this.form.status = this.form.type == 0?0:6
            this.form.makeStatus = 0
            this.form.userId = this.$store.getters.userId
            this.form.title = parseTime(this.form.title, "{y}-{m}-{d}")
            addTaskerp(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除任务erp编号为"' + ids + '"的数据项？').then(function() {
        return delTaskerp(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      exportExcel(this.queryParams).then(() => {
        this.$alert('任务创建成功，请到<strong style="color: #00afff">任务中心</strong>查看进度!', '提示', {
          dangerouslyUseHTMLString: true
        }).catch(()=>{});
      })
    },
  }
};
</script>

<style>
::-webkit-scrollbar {
  width: 0.07rem;
  height: 10px !important;
}
::-webkit-scrollbar-thumb {
  background: black !important;
}
</style>
